(function () {
  new Vue({
    el: '#commissionManagement',
    data() {
      return {
        currentPage: 1,
        limit: ['10'],
        totalPage: 0,
        totalCount: 0,
        columns: '',
        orders: '',
        pageLimits: [{name: '10', code: '10'}, {name: '15', code: '15'}, {name: '20', code: '20'}],
        keyword: '',
        payment_deadline_begin: '',
        payment_deadline_end: '',
        begin_date: '',
        end_date: '',
        project_id: [],
        building_id: [],
        floor_id: [],
        unit_id: [],
        projectList: [],//所有项目
        projectListIds:'',//所有项目ID
        buildingList: [], //所有楼栋（搜索）
        floorList: [],//所有楼层（搜索）
        unitList: [],//所有单元（搜索）
        commisson_confirm_flag: '',
        isExtenseFlag: false, //展开与收起
        billOverTypeData: [{ name: '正常', code: 'NM', num: '0' }, { name: '即将到期', code: 'DU', num: '0' }, { name: '已逾期', code: 'OD', num: '0' }], //筛选项(逾期情况)
        selectedOverTypeCode: [],//筛选状态(逾期情况)
        billStateData: [{ name: '待提交', code: 'WTJ', num: '0' }, { name: '已提交', code: 'YTJ', num: '0' }],//筛选项（处理状态）
        selectedBillStateCode: [],//筛选项（处理状态）
        listObj: { turnoverInfoListPageVO: [] },
        //自定义开始
        configType: 'WZ', //默认完整WZ     JD简单，WZ完整，自定义配置PZ
        module: '#',
        headArr: [],
        sortTableTitle: [],
        isScroll: false,
        isShowTableLayer: false,
        dateTimeUpdate: [],
        isActiveCode: '#',
        tbTitleWidth: {},
        listObj: {
          commissionInfoList: []
        },
        groupId:null,
        groupOneData:[],
        groupTwoData:[],
        groupThreeData:[],
        selectedGroupData:[],
      }
    },
    filters: {
      formatUndefined: function (item) {
        if (!item) return '--'
        if (typeof item == 'number') {
        	if (!isNaN(item) && item.toString().length == 13) {
        		return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
        	};
        }
        return item
      },
    },
    created() {
      hlSelectUi()
    },
    mounted() {
      this.getprojectData();
      this.initSortable();
      this.configTypeDt();
    },
    methods: {
      selectBillMenu(){
        this.currentPage = 1
        this.getCommissionData()
      },
      openSearch() {
        if (this.isExtenseFlag == true) {
          this.isExtenseFlag = false;
          return false;
        }
        if (this.isExtenseFlag == false) {
          this.isExtenseFlag = true;
          return false;
        }
      },
      // 抽成管理列表
      getCommissionData() {
        const self = this

        hlhttp.get({
          url: 'bill/commission/_search',
          data: {
            "keyword": this.keyword || '#',
            "payment_deadline_begin": this.payment_deadline_begin || '#',
            "payment_deadline_end": this.payment_deadline_end || '#',
            "begin_date": this.begin_date || '#',
            "end_date": this.end_date || '#',
            "project_id": this.project_id.length ? this.project_id[0] : this.projectListIds,
            "group_id": this.groupId || '#',
            "building_id": this.building_id.length ? this.building_id[0] : '#',
            "floor_id": this.floor_id.length ? this.floor_id[0] : '#',
            "unit_id": this.unit_id.length ? this.unit_id[0] : '#',
            "overdue_state": this.selectedOverTypeCode.length ? this.selectedOverTypeCode.join() : '#',
            "commisson_confirm_flag": this.selectedBillStateCode.length ? this.selectedBillStateCode.join() : '#',
            "page": this.currentPage,
            "limit": this.limit[0],
            "columns": this.columns || '#',
            "orders": this.orders || '#',
          },
          success: function (res) {
            self.listObj = res
            self.totalCount = res.totalCount
            self.totalPage = res.totalPage
            self.getStatuscountData();
          }
        })
      },
      // 抽成管理列表数量统计（待录入数量、已录入数量、已提交数量 ）
      getStatuscountData() {
        var self = this
        hlhttp.get({
          url: 'bill/commission/_search/status_count',
          data: {
            "keyword": this.keyword || '#',
            "payment_deadline_begin": this.payment_deadline_begin || '#',
            "payment_deadline_end": this.payment_deadline_end || '#',
            "begin_date": this.begin_date || '#',
            "end_date": this.end_date || '#',
            "project_id": this.project_id.length ? this.project_id[0] : this.projectListIds,
            "building_id": this.building_id.length ? this.building_id[0] : '#',
            "floor_id": this.floor_id.length ? this.floor_id[0] : '#',
            "unit_id": this.unit_id.length ? this.unit_id[0] : '#',
          },
          success: function (res) {
            self.billOverTypeData.forEach(el => {
              if(el.code == 'NM') el['num'] = res['nMcount']
              if(el.code == 'DU') el['num'] = res['dUcount']
              if(el.code == 'OD') el['num'] = res['oDcount']
            })
            self.billStateData.forEach(el => {
              if(el.code == 'WTJ') el['num'] = res['wTJcount']
              if(el.code == 'YTJ') el['num'] = res['yTJcount']
            })
          }
        })
      },
      // 重置筛选状态
      resetStatus() {
        this.selectedOverTypeCode = []
        this.selectedBillStateCode = []
        this.currentPage = 1
        this.getCommissionData()
      },
      //获取项目
      getprojectData() {
        const self = this
        hlhttp.get({
          url: 'user/projects',
          success: (res) => {
            res = hlArrayUtil.removeRepeat(res, 'projectId')
            self.projectList = hlArrayUtil.replaceData(res, [{key: 'projectName', rKey: 'name'}, {key: 'projectId', rKey: 'code'}]);

            let arr = []
            res.map(item =>{
              arr.push(item.projectId)
            })

            self.projectListIds = arr.join(',')
            self.getCommissionData()
            self.getStatuscountData()


          }
        })
      },
      // 获取一级组合数据
      getGroupPrimaryData(data){
        const self = this
        self.project_id = [data[0].code]
        self.groupId = null
        self.building_id = []
        self.floor_id = []
        self.unit_id = []
        self.buildingList = []
        self.floorList = []
        self.unitList = []
        self.selectedGroupData = []
        self.getGroupData().then(data => {
          self.groupOneData = hlArrayUtil.replaceData( data, [{key: 'id', rKey: 'code'}] );
        })
        self.getBuildingData()
      },
      // 选取一级组合数据
      selectOneGroup(res){
        const self = this
        this.groupId = res['cur']['code']
        this.getGroupData().then(data => {
          self.groupTwoData = hlArrayUtil.replaceData( data, [{key: 'id', rKey: 'code'}] )
          self.getBuildingData()
        })
      },
      // 选取二级组合数据
      selectTwoGroup(res){
        const self = this
        this.groupId = res['cur']['code']
        this.getGroupData().then(data => {
          self.groupThreeData = hlArrayUtil.replaceData( data, [{key: 'id', rKey: 'code'}] )
          self.getBuildingData()
        })
      },
      // 选取三级组合数据
      selectThreeGroup(res){
        this.groupId = res['cur']['code']
      },
      getGroupData(){
        const self = this

        return new Promise(resolve => {
          hlhttp.get({
            url:'project/grouping_info/_subclass',
            data:{'project_id':self.project_id[0] , 'grouping_id':self.groupId || '#' },
            success:function(data){
              resolve(data)
            }
          })
        })
      },
      //获取楼宇
      getBuildingData() {
        const self = this
        hlhttp.get({
          url: 'project/grouping/_building',
          data: { project_id: self.project_id.length ? self.project_id[0] : '#'  , grouping_id:self.groupId || '#'},
          success: (res) => {
            this.buildingList = hlArrayUtil.replaceData(res, [{key: 'buildingId', rKey: 'code'}]);
          }
        })
      },
      //获取楼层
      getfloorData(id, type) {
        let data = {}
        data.project_id = this.project_id[0]
        data.building_id = id
        hlhttp.get({
          url: 'building/floors',
          data: data,
          success: (res) => {
            this.floorList = hlArrayUtil.replaceData(res, [{key: 'floorName', rKey: 'name'}, {key: 'floorId', rKey: 'code'}]);
          }
        })
      },
      //获取单元
      getunitData(id) {
        let data = {}
        data.project_id = this.project_id[0]
        data.building_id = this.building_id[0]
        data.floor_id = id
        hlhttp.get({
          url: 'floor/units',
          data: data,
          success: (res) => {
            this.unitList = hlArrayUtil.replaceData(res, [{key: 'unitName', rKey: 'name'}, {key: 'unitId', rKey: 'code'}]);
          }
        })
      },
      selectProject(arr) {
        this.project_id = [arr[0].code]
        this.building_id = []
        this.floor_id = []
        this.unit_id = []
        this.buildingList = []
        this.floorList = []
        this.unitList = []
      },
      //选中楼栋
      selectBuilding(arr) {
        this.building_id = [arr[0].code]
        this.floor_id = []
        this.unit_id = []
        this.floorList = []
        this.unitList = []
        this.getfloorData(arr[0].code)
      },
      //选中楼层
      selectFloor(arr) {
        this.floor_id = [arr[0].code]
        this.unit_id = []
        this.unitList = []
        this.getunitData(arr[0].code)
      },
      //选中单元
      selectUnit(arr) {
        this.unit_id = [arr[0].code]
      },
      // 设置分页数量
      setMoreNum(arr) {
        this.limit = [arr[0].code]
        this.currentPage = 1
        this.getCommissionData()
      },
      search() {
        this.currentPage = 1
        this.getCommissionData()
      },
      //重置
      reset() {
        this.currentPage = 1
        this.keyword = '',
        this.columns = '',
        this.orders = '',
        this.payment_deadline_begin = '',
        this.payment_deadline_end = '',
        this.begin_date = '',
        this.end_date = '',
        this.project_id = []
        this.groupId = null
        this.building_id = []
        this.floor_id = []
        this.unit_id = []
        this.buildingList = [],
        this.floorList = [],
        this.unitList = [],
        this.isActiveCode = '',
        this.selectedOverTypeCode = []
        this.selectedBillStateCode = []
        this.selectedGroupData = []
        this.getCommissionData()
      },
      // 前往抽成详情
      goTodetail(id) {
        hlUrlUtil.goTo('commissionDetail', { id: id, ddtab: true }, true)
      },
      //更新时间
      sortBySTTime(item) {
        if (this.dateTimeUpdate.indexOf(item.value) == -1) return
        this.isActiveCode = item.value;
        this.orders = this.orders == 'ASC' ? 'DESC' : 'ASC';
        this.columns = item.orderName
        this.getTurnoverData();
      },
      //获取自定义表头配置状态
      configTypeDt() {
        hlhttp.get({
          url: 'configure/customize_column_header/type',
          data: { module: 'HETN_CCGL' },
          success: (data) => {
            this.configType = data.configType;
            this.customizeHeaderDt()
          }
        })
      },
      //获取自定义表头配置信息
      customizeHeaderDt() {
        hlhttp.get({
          url: 'configure/customize_column_header',
          data: { module: 'HETN_CCGL' },
          success: (data) => {
            data.customConfigList.map(item => {
              item.seq = Number(item.seq)
              item.customSeq = Number(item.customSeq)
              item.isActive = 'N'
              if (item.orderFlag == 'Y') {
                this.dateTimeUpdate.push(item.value)
              }
            })
            if (this.configType == 'JD' || this.configType == 'WZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('seq'))
            }
            if (this.configType == 'PZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('customSeq'))
            }
            this.headArr = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle = JSON.parse(JSON.stringify(data.customConfigList));
            this.tbTitleWidthCalculation()
          }
        })
      },
      //宽度计算
      tbTitleWidthCalculation() {
        let w = 0, flag = false;
        this.headArr.map(item => {
          if (item.value == '序') {
            flag = true;
          }
        })
        w = this.headArr.length * 120 - 80;
        this.tbTitleWidth = { width: w + 'px' }
      },
      //弹窗显示
      showTableLayer() {
        this.isShowTableLayer = true;
      },
      //关闭自定义表头弹窗
      closeTableLayer() {
        this.isShowTableLayer = false;
      },
      //简单完整配置切换
      selectTableType(type) {
        this.configType = type;
        this.changeTableType(type)
        this.updateConfigType()
      },
      //更新自定义表头配置状态
      updateConfigType() {
        hlhttp.put({
          url: 'configure/customize_column_header/type',
          data: { module: 'HETN_CCGL', config_type: this.configType },
          success: () => {
            this.configTypeDt()
          }
        })
      },
      //改变头部
      changeTableType(type) {
        if (type == 'JD' || type == 'WZ') {
          this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('seq'))
        }
        if (type == 'PZ') {
          this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('customSeq'))
        }
        this.tbTitleWidthCalculation()
      },
      //显示某个自定义标题
      selectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'Y'
      },
      //关闭某个自定义标题
      cancelSelectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'N'
      },
      showhighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'Y'
      },
      removehighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'N'
      },
      //鼠标经过显示scroll
      showScroll() {
        this.isScroll = true;
      },
      //鼠标离开关闭scroll
      hideScroll() {
        this.isScroll = false;
      },
      // 确定提交自定义表格
      confirmSubmitTable() {
        let dataArr = [];
        this.sortTableTitle.map((item, index) => {
          dataArr.push({
            "base_flag": item.baseFlag,
            "seq": item.seq,
            "custom_show_flag": item.customShowFlag,
            "custom_seq": index,
            "custom_display_name": item.customDisplayName ? item.customDisplayName : '#',
            "dict_code": item.dictCode,
            "config_type": item.configType,
            "name": item.name,
            "value": item.value,
            "union_table_part": item.unionTablePart,
            "flex": item.flex,
            "style_width": item.styleWidth,
            "order_flag": item.orderFlag,
            "order_name": item.orderName
          })
        })

        hlhttp.put({
          url: 'configure/customize_column_header',
          data: {
            module: 'HETN_CCGL',
            custom_config: JSON.stringify(dataArr)
          },
          success: (data) => {
            hl.toast('操作成功')
            this.closeTableLayer()
            this.updateConfigType()
          }
        })
      },
      // 初始化拖动排序
      initSortable() {
        const self = this;
        const el = document.getElementById('sortableTable');
        Sortable.create(el, {
          draggable: 'ul',
          onEnd(evt) {
            const beginIndex = evt.oldIndex;
            const endIndex = evt.newIndex;
            const newArr = JSON.parse(JSON.stringify(self.sortTableTitle));
            newArr.splice(endIndex, 0, newArr.splice(beginIndex, 1)[0])
            self.sortTableTitle = [];
            self.$nextTick(() => {
              self.sortTableTitle = newArr
            })
          }
        })
      },
    },
  })
}())
